<template>
  <div>
    <form-content
      :rules="rules"
      :form-items="formItems"
      :beforeSubmit="beforeSubmit"
      :handleInitFormData="handleInitFormData"
      :submitApi="submitApi"
      :formStateInit="detail"
      :preview="preview"
      :afterSubmit="afterSubmit"
      @formChange="formChange"
    >
    </form-content>
  </div>
</template>

<script>
import { ref, toRefs, toRef, reactive, onMounted} from 'vue';
import { message } from 'ant-design-vue';
import { useRouter } from 'vue-router';
import { formItems, formItems2Rules } from './config';
import { add, info, update } from '../api';

export default {
  data() {
    return {
      formItems
    };
  },
  setup(props, context) {
    const router = useRouter();
    const {query, name: routeName} = router.currentRoute.value;
    const rules = ref(formItems2Rules);
    const state = reactive({
      preview: routeName.includes('detail'),
      detail: {}
    })
    const afterSubmit = (res) => {
      res.code == 0 && message.success('提交成功');
      router.push({name: 'pluginList'});
    };
    const beforeSubmit = (data) => {
      console.log(data,'beforeSubmit');
      data.custom = JSON.stringify({
        pic: data.pic[0],
        jump_type: data.jump_type,
        url: data.url,
        rate: data.rate
      })
      return data;
    };
    const handleInitFormData = (data) => {
      return data;
    }

    const formChange = (current, formState, source, item ) => {
      if (current.name === 'category_id') {
        const [v, vdata] = item;
        if (v) {
          formState.company_id = vdata.company_id;
        }
      }
    }
    const submitApi = (p) => {
      p.type = 'popup';
      p.id = query.id ? Number(query.id) : query.id;
      return query.id ? update(p) : add(p);
    }

    onMounted(() => {
      if (query.id) {
        info({id: Number(query.id)}).then(res => {
          const {data} = res;
          const {custom} = data;
          if (custom) {
            const infos = JSON.parse(custom);
            Object.assign(data,infos,{
              pic: [infos.pic]
            });
          }
          state.detail = data;
        })
      }
    });
    return {
      ...toRefs(state),
      submitApi,
      formChange,
      handleInitFormData,
      beforeSubmit,
      afterSubmit,
      rules,
    };
  },
};
</script>

<style scoped>
.box-list{
  position: relative;
  border:1px solid #eee;
  padding-top:10px;
  margin-top: 10px;
}
.list-del-btn{
  position:absolute;
  right: 10px
}
</style>